package cc.ufinity.networkdiagnose.view;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Window;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TabHost;
import android.widget.Toast;
import cc.ufinity.networkdiagnose.app.App;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.UpdateInfo;
import cc.ufinity.networkdiagnose.manager.UpdateVersionManager;
import cc.ufinity.networkdiagnose.service.TaskService;
import cc.ufinity.networkdiagnose.widget.HttpConfigWidget;
import cc.ufinity.networkdiagnose.widget.PingConfigWidget;

public class MainActivity extends TabActivity implements OnCheckedChangeListener {
    /** Called when the activity is first created. */
	private RadioGroup radioGroup;
    private TabHost tabHost;
    private Intent ihome;
    private Intent itask;
    private Intent itest;
    private Intent icfg;
    
    private RadioButton task;
    private  RadioButton tesk;
    private RadioButton home;
    private RadioButton cfg;
    public Activity ctx;
	//private final static String TAB_TAG_HOME="tab_tag_home";
    private final static String TAB_TAG_HOME="tab_tag_check";
	private final static String TAB_TAG_TEST="tab_tag_test";
	private final static String TAB_TAG_TASK="tab_tag_task";
	private final static String TAB_TAG_CFG="tab_tag_cfg";
	
	public static final int IS_UPDATA = 0;
	public static final int UPDATA_CLIENT = 1;
	public static final int GET_UNDATAINFO_ERROR = 2;
	public static final int DOWN_ERROR = 3;
	public static final int KEEP_VERSION = 4;
	
	private UpdateVersionManager updateManager = null;
    private String version = null;
    private UpdateInfo info = null;
    
  /*//通知显示内容  
    private PendingIntent pd; 
	//通知管理器  
	private NotificationManager nm;  
    private int Notification_ID_BASE = 110;  
    private Notification baseNF; */
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.ctx = this;

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //初始化ping的次数为1；默认http网址为www.baidu.com
		SharedPreferences settings = this.getSharedPreferences(PingConfigWidget.PREFS_PING_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        String Number = settings.getString(PingConfigWidget.PREFS_PING_KEY, "");
        if(Number.equals("") || Number.equals(null)){
	        editor.putString(PingConfigWidget.PREFS_PING_KEY, "1");
	        editor.commit();
        }
        
        settings = this.getSharedPreferences(HttpConfigWidget.PREFS_HTTP_NAME, 0);
        editor = settings.edit();
        String url = settings.getString(HttpConfigWidget.PREFS_HTTP_KEY, "");
        if(url.equals("") || url.equals(null)){
        	editor.putString(HttpConfigWidget.PREFS_HTTP_KEY, "www.baidu.com");
            editor.commit();	
        }
        
        SharedPreferences settings1 = ctx.getSharedPreferences(GlobalApp.CFG_SERVER, 0);
        String ip = settings1.getString(GlobalApp.CFG_SERVER_IP, "");
        GlobalApp.FTP = ip;
        //开启taskService
		 //打开或创建preTasks.db数据库  
        SQLiteDatabase db = openOrCreateDatabase("preTasks.db", Context.MODE_PRIVATE, null);  
      //创建person表  
        try {
            db.execSQL("create table tasks (_id integer primary key autoincrement, "
            		+ "taskid varchar(100) not null)"); 
		} catch (Exception e) {
			// TODO: handle exception
		}
		db.close();
         startService(new Intent(this, TaskService.class));	

     // 自定义titlebar
		//requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.main);
		/*getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.title);*/
         
		  task=(RadioButton)findViewById(R.id.radio_task);
			tesk=(RadioButton)findViewById(R.id.radio_test);
			home=(RadioButton)findViewById(R.id.radio_home);
			cfg=(RadioButton)findViewById(R.id.radio_cfg);
		
        radioGroup = (RadioGroup)this.findViewById(R.id.radioGroup);
//        radioGroup.setOnCheckedChangeListener(this);
    //----------------------------------------------------------  
        radioGroup.setOnCheckedChangeListener(this);
    //----------------------------------------------------------
        prepareIntent();
        setupIntent();
        String test= (String)(this.getIntent().getExtras().getString("intentFlag"));
        if(test.equals("taskService")){
        	radioGroup.getCheckedRadioButtonId ();//--获取选中按钮的id
        	radioGroup.clearCheck ();//---清除选中状态
        	radioGroup.check(R.id.radio_task);//---通过参入选项id来设置该选项为选中状态如果传递-1作为指定的选择标识
        	this.tabHost.setCurrentTabByTag(TAB_TAG_TASK);
        }
        //定时更新FTP账号（5分钟一次）
        final Timer timer = new Timer(true);
        GlobalApp.isGotFtp = false;
        timer.schedule(new TimerTask() {
        	
			@Override
			public void run() {
				if(GlobalApp.isGotFtp) {
					timer.cancel();
				} else {
					DBManager db = new DBManager(ctx);
					FTPConfig ftp = db.getFtp2();
	    	        if(ftp!=null) {
	    	        	db.saveFtp(ftp);  
	    	        } 
	    	        db.release();
				}
				
			}
		}, 500, 2 * 60 * 1000);
        
        new Thread() {

			@Override
			public void run() {
				updateManager = new UpdateVersionManager(MainActivity.this, handler);
		        try {
		        	version = updateManager.getVersionName();
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(version == null) {
					System.out.println("获取版本号失败！");
				} else {
					System.out.println("版本号：" + version);
				}
				boolean isGotAPK = false;
				boolean isRun = false;
				while(!isGotAPK) {
					if(!isRun) {
						isRun = true;
						info = updateManager.getUpdataInfo(GlobalApp.url_UpdateAPK);
						//info = updateManager.getUpdataInfo("http://192.168.1.108:80/update.xml");
						if(info == null) {
							System.out.println("UpdateAPK 服务器故障");
							isRun = false;
						} else {
							Message msg = handler.obtainMessage();
							if(info.getVersion().equals(version)) {
								msg.what = KEEP_VERSION;
							} else {
								msg.what = IS_UPDATA;
							}
							handler.sendMessage(msg);
							isGotAPK = true;
						}
					}
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
        	
        }.start();
        
        new App(this);
        
    }
    
    Handler handler = new Handler(){
		
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case IS_UPDATA: 
				//对话框通知用户升级程序 
				System.out.println("版本号不同 ,提示用户升级   = " + info.getVersion() + " + " + info.getUrl());
				System.out.println("---------- 显示");
				updateManager.showTree();
				updateManager.showUpdataDialog();
				break;
			case UPDATA_CLIENT:
				//下载应用程序--进度条显示 
				System.out.println("通知用户升级程序");
				updateManager.downLoadApk(info.getUrl());
				break;
			case GET_UNDATAINFO_ERROR:
				//服务器超时 
				System.out.println("获取服务器更新信息失败");
				break;	
			case DOWN_ERROR:
				//下载apk失败
				System.out.println("下载新版本失败");
				Toast.makeText(MainActivity.this, "更新版本失败", Toast.LENGTH_LONG).show();
				break;	
			case KEEP_VERSION:
				//版本号相同，删除   .zip和.apk文件
				System.out.println("版本号相同无需升级 --> 删除   .zip和.apk文件");
				updateManager.deleteZIP_APK();
				break;
			}
		}
	};
    
	@Override
	public void onCheckedChanged(RadioGroup rGroup, int checkId) {
		switch(checkId){
		case R.id.radio_task://任务测试
			setNowTest(2);
			tesk.setBackgroundResource(R.drawable.jt004);
			task.setBackgroundResource(R.drawable.jt00115643);
			home.setBackgroundResource(R.drawable.jt002);
			cfg.setBackgroundResource(R.drawable.jt003);
			this.tabHost.setCurrentTabByTag(TAB_TAG_TASK);
			break;
		case R.id.radio_cfg:
			tesk.setBackgroundResource(R.drawable.jt004);
			task.setBackgroundResource(R.drawable.jt001);
			home.setBackgroundResource(R.drawable.jt002);
			cfg.setBackgroundResource(R.drawable.jt00313333);
			this.tabHost.setCurrentTabByTag(TAB_TAG_CFG);
			break;
		case R.id.radio_test: //网络测试
			setNowTest(1);
			tesk.setBackgroundResource(R.drawable.jt00411111);
			task.setBackgroundResource(R.drawable.jt001);
			home.setBackgroundResource(R.drawable.jt002);
			cfg.setBackgroundResource(R.drawable.jt003); 
			this.tabHost.setCurrentTabByTag(TAB_TAG_TEST);
			break;
		case R.id.radio_home: //验收测试
			setNowTest(3);
			tesk.setBackgroundResource(R.drawable.jt004);
			task.setBackgroundResource(R.drawable.jt001);
			home.setBackgroundResource(R.drawable.jt0021678876);
			cfg.setBackgroundResource(R.drawable.jt003);
			this.tabHost.setCurrentTabByTag(TAB_TAG_HOME);
			break;
		}
		
	}
	
	private void setNowTest(int i) {
		switch(i) {
		case 1:
			GlobalApp.is_NET_TEST = true;
			GlobalApp.is_TASK_TEST = false;
			GlobalApp.is_CHECK_TEST = false;
			break;
		case 2:
			GlobalApp.is_NET_TEST = false;
			GlobalApp.is_TASK_TEST = true;
			GlobalApp.is_CHECK_TEST = false;
			break;
		case 3:
			GlobalApp.is_NET_TEST = false;
			GlobalApp.is_TASK_TEST = false;
			GlobalApp.is_CHECK_TEST = true;
			break;
		}
	}
	
	private void prepareIntent(){
	//	ihome = new Intent(this,HomeActivity.class);   //无线环境
		ihome = new Intent(this,CheckActivity.class);   //验收测试
		itask = new Intent(this,TaskActivity.class);   //任务测试
		itest = new Intent(this,TestActivity.class);   //网络测试
		icfg = new Intent(this,CfgActivity.class);     //系统管理
		
	}
	
	private void setupIntent(){
		tabHost = this.getTabHost();
		//tabHost.addTab(buildTabSpec(TAB_TAG_TEST, R.string.meun_test, R.drawable.tether, itest));
		tabHost.addTab(buildTabSpec(TAB_TAG_TEST, R.string.meun_test, R.drawable.jt004, itest));
		//tabHost.addTab(buildTabSpec(TAB_TAG_HOME, R.string.meun_home, R.drawable.home, ihome));
		tabHost.addTab(buildTabSpec(TAB_TAG_HOME, R.string.meun_check, R.drawable.jt002, ihome));
		tabHost.addTab(buildTabSpec(TAB_TAG_TASK, R.string.meun_task, R.drawable.jt001, itask));
		tabHost.addTab(buildTabSpec(TAB_TAG_CFG, R.string.meun_cfg, R.drawable.jt003, icfg));
	}
	
	private TabHost.TabSpec buildTabSpec(String tag, int resLabel, int resIcon, final Intent content) {
		return this.tabHost.newTabSpec(tag).setIndicator(getString(resLabel),
				getResources().getDrawable(resIcon)).setContent(content);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (KeyEvent.KEYCODE_BACK == keyCode) {

		}
		return super.onKeyDown(keyCode, event);
	}
	 
	
	
}
